import axios from 'axios'
// axios.defaults.baseURL = 'http://api-cm.zhangtl.com:8000'
const url = {
  getNewFactor: 'http://btb-cm.zhangtl.com:8302/latest_factors',
  getHotFactor: '/oxapi2/picking/specialHot',
  getAllFactors: 'http://btb-cm.zhangtl.com:8302/factors',
  getStockCodes: 'http://btb-cm.zhangtl.com:8302/stocks',
  // getHotNews: 'http://btb-cm.zhangtl.com:8301/hot-news/2018-1-12/1'
  getHotNews: 'https://api-cm.zhangtl.com/oxapi2/news/v2/essence_by_date'
}

class API {
  constructor ({url, params}) {
    this.url = url
    this.params = params
    let _obj = {}
    Object.keys(url).forEach((v) => {
      _obj[v] = this.GET.bind(null, url[v])
    })
    console.log()
    Object.assign(this, _obj)
  }
  ISGET () {
  }

  /**
   * config 请求配置
   * @returns {{baseURL: string, withCredentials: boolean, transformRequest: *[], responseType: string}}
   * @constructor
   */
  CONFIG () {
    let config = {
      baseURL: 'https://api-cm.zhangtl.com:443',
      withCredentials: true,
      transformRequest: [function (data) {
        return data
      }]
    }
    return config
  }

  /**
   * request 请求
   * @param _url
   * @param _conf
   * @param _params
   * @constructor
   */
  REQUEST (_url, _conf, _params) {
    let _config = Object.assign(_conf, {url: _url}, _params)
    return new Promise((resolve, reject) => {
      axios.request(_config).then(res => {
        if (res.status === 200) {
          if (!res.data.code || res.data.code !== 0) {
            resolve(res.data)
          }
        }
      }).catch(err => {
        reject(err)
      })
    })
  }

  /**
   * get 请求
   * @param url
   * @param params
   * @constructor
   */
  GET (url, params) {
    return new Promise((resolve, reject) => {
      axios.get(url, params).then(res => {
        // console.log('get', res)
        if (res.status === 200) {
          if (!res.data.code || res.data.code !== 0) {
            resolve(res.data)
          }
        }
      }).catch(err => {
        reject(err)
      })
    })
  }

  /**
   * post 请求
   * @param url
   * @param params
   * @constructor
   */
  POST (url, params) {
    return new Promise((resolve, reject) => {
      axios.post(url, params).then(res => {
        // console.log('post', res)
        if (res.status === 200) {
          if (!res.data.code || res.data.code !== 0) {
            resolve(res.data.Data)
          }
        }
      }).catch(err => {
        reject(err)
      })
    })
  }
}

export default new API({
  url
})
